#include "oal/WavFile.h"

using namespace Oal;

WavFile::WavFile(const std::string& filename)
{
    LoadData(filename);
}

bool WavFile::LoadData(const std::string& filename)
{
    std::ifstream file(filename, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "cannot open file " << filename << std::endl;
        return false;
    }

    file.read(reinterpret_cast<char*>(&m_Header), sizeof(Header));
    if (m_Header.riff[0] != 'R' || m_Header.riff[1] != 'I' || m_Header.riff[2] != 'F' || m_Header.riff[3] != 'F' ||
        m_Header.wave[0] != 'W' || m_Header.wave[1] != 'A' || m_Header.wave[2] != 'V' || m_Header.wave[3] != 'E') {
        std::cerr << "deserted wav file " << filename << std::endl;
        return false;
    }

    m_Data.resize(m_Header.dataSize);
    file.read(m_Data.data(), m_Header.dataSize);
    return true;
}

void WavFile::FreeData()
{
    m_Data = {};
}

int WavFile::GetFormat() const
{
    int format;
    if (m_Header.numChannels == 1) {
        format = (m_Header.bitsPerSample == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
    }
    else {
        format = (m_Header.bitsPerSample == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
    }
    return format;
}